<template>
  <view class="info-tags">
    <view class="info-tags-list">
      <view
        class="info-tag-wrapper"
        v-for="(item, index) in localItems?.cardsTagList"
        :key="item.id"
        @click="handleTagClick(item)"
      >
        <view
          class="info-tag-item"
          :class="{ selected: tagDisplayList[index]?.key != 'all' }"
        >
          <view class="info-tag-content">
            <view
              :style="{
                color:
                  tagDisplayList[index]?.key !== 'all'
                    ? 'var(--text-active-primary)'
                    : 'var(--text-primary)',
              }"
              >{{ tagDisplayList[index].name }}
            </view>

            <uv-icon
              v-if="item.modelType === 'radio'"
              name="arrow-down"
              :color="
                tagDisplayList[index]?.key != 'all'
                  ? 'var(--text-active-primary)'
                  : 'var(--text-primary)'
              "
              size="12"
            />
            <uv-icon
              v-else-if="item.modelType === 'CustomCardMultipleSelection'"
              name="list"
              :color="
                tagDisplayList[index]?.key != 'all'
                  ? 'var(--text-active-primary)'
                  : 'var(--text-primary)'
              "
              size="12"
            />
          </view>
        </view>
      </view>
    </view>

    <uv-modal
      :key="currentOptions?.id"
      ref="modalRef"
      negativeTop="60%"
      :show-confirm-button="false"
    >
      <view class="info-tags-modal">
        <view class="info-tags-radio-modal" v-if="currentOptions?.modelType === 'radio'">
          <uv-radio-group
            v-model="localItems.cardsTagValue[currentOptions.id]"
            @change="radioHandleChange"
            placement="column"
            :customStyle="{ width: '100%' }"
            activeColor="var(--text-active-primary)"
          >
            <uv-radio
              :customStyle="{ margin: '6rpx', padding: '12rpx 0' }"
              v-for="item in currentOptions?.option"
              :key="item.key"
              :label="item.name"
              :name="item.key"
            ></uv-radio>
          </uv-radio-group>
        </view>
      </view>
    </uv-modal>
  </view>
</template>

<script setup>
import { ref, computed, watch, nextTick } from "vue";
import { clone } from "radash";

const props = defineProps({
  items: {
    type: Object,
    default: () => ({}),
  },
});

const emit = defineEmits(["update:result", "change"]);

const localItems = ref(clone(props.items));
const modalRef = ref();
const currentOptions = ref({});

const tagDisplayList = computed(() => {
  // 如果 cardsTagList 不存在或为空，返回空数组
  if (!localItems.value?.cardsTagList || !Array.isArray(localItems.value.cardsTagList)) {
    return [];
  }

  return localItems.value.cardsTagList.map((item) => {
    // 确保 item 和 item.id 存在
    if (!item || !item.id) {
      return { name: "", key: "all" };
    }

    // 获取当前选中的 key，默认为 "all"
    const selectedKey = localItems.value.cardsTagValue?.[item.id] ?? "all";

    // 查找对应的 option
    const option = item.option?.find((i) => i.key === selectedKey);

    // 确定 name：优先使用 allName（当 selectedKey 为 "all" 时），否则使用 option 的 name
    let name = "";
    if (selectedKey === "all") {
      name = item.allName || item.option?.[0]?.name || "";
    } else {
      name = option?.name || item.option?.[0]?.name || item.allName || "";
    }

    // 确定 key：优先使用 option 的 key，否则使用默认值
    const key = option?.key || item.option?.[0]?.key || "all";

    return { name, key };
  });
});

const handleTagClick = async (item) => {
  currentOptions.value = clone(item);
  await nextTick();
  if (!localItems.value?.cardsTagValue?.[currentOptions.value?.id]) {
    localItems.value.cardsTagValue[currentOptions.value?.id] = "all";
  }
  modalRef.value.open();
};

const radioHandleChange = () => {
  modalRef.value.close();
};

watch(
  () => props.items,
  (newItems) => {
    localItems.value = clone(newItems);
  },
  { deep: true }
);
</script>

<style lang="scss" scoped>
.info-tags {
  height: auto;

  .info-tags-list {
    display: flex;
    flex-wrap: wrap;
    gap: 10rpx;
    padding: 10rpx 10px;

    .info-tag-wrapper {
      flex-shrink: 0;
    }

    .info-tag-item {
      background-color: var(--color-primary-light);
      color: var(--color-primary);
      font-size: 24rpx;
      padding: 8rpx 20rpx;
      border-radius: 999rpx;
      border: 2rpx solid var(--border-color);
      max-width: 200rpx;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      box-sizing: border-box;
      transition: all 0.2s ease;
      text-align: center;
      .info-tag-content {
        display: flex;
        align-items: center;
        gap: 4px; /* 图标与文字间距 */
      }
      &:active {
        transform: scale(0.96);
        opacity: 0.8;
      }

      &.selected {
        background-color: var(--color-primary);
        color: var(--border-active-color);
        border-color: var(--border-active-color);
        box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.1);
      }
    }
  }

  .info-tags-modal {
    width: 100%;
    height: 100%;

    .info-tags-radio-modal {
      width: 100%;
      height: 100%;
    }
  }
}
</style>
